
.PHONY: deploy 
# 需要改的地方
include .env

# 公共变量
SSH_CMD =echo $(SSH_HOST) && ssh -o StrictHostKeyChecking=no -i ${SSH_KEY} $(SSH_HOST)
PROJECT_NAME = $(notdir $(CURDIR))
HOME_DIR =~/$(PROJECT_NAME)
## 新机器执行命令
pre: docker-env
	@echo "no need to run this command again"




## 部署相关
deploy: 
	@scp  -i ${SSH_KEY}  -r . $(SSH_HOST):$(HOME_DIR)
	@$(SSH_CMD) "cd $(HOME_DIR)/deploy &&  docker compose pull && docker compose up -d"
	make ps
	make log


## 环境相关
docker-env:
	@echo "开始检测docker环境"
	@$(SSH_CMD) "command -v docker >/dev/null 2>&1 || { echo 'Docker not found, installing...'; if [ -f /etc/alinux-release ]; then curl -fsSL http://shell.huthrc.top/docker-centos.sh | bash ; else curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun; fi; }"
	@$(SSH_CMD) "sudo systemctl start docker"
	@$(SSH_CMD) "sudo systemctl enable docker"
	@$(SSH_CMD) "docker -v"
	@echo "docker installed"


include .env
## caddy配置反向代理
proxy:
	@$(SSH_CMD) "caddy reverse-proxy --from $(FROM)  --to $(TO)"

## 查看全部的caddy反向代理
proxy-ls:
	@$(SSH_CMD) "ps -eo cmd | grep reverse-proxy"



## 工具类
ip:
	@$(SSH_CMD) "curl -s ip.me"

## SSH 
ssh:
	@$(SSH_CMD) 

sh:
	@$(SSH_CMD) $(cmd)






## docker 容器管理
log:
	@$(SSH_CMD) "cd $(HOME_DIR)/deploy && docker compose logs -f"

ps:
	@$(SSH_CMD) "cd $(HOME_DIR)/deploy && docker compose ps"











## 资源监控
TOP_CMD = "ps -eo pid,%cpu,%mem,rss,vsz,cmd --sort -%mem | awk 'NR==1 { printf \"%-10s %-10s %-10s %-10s %-10s %s\\n\", \$$1, \$$2, \$$3, \"RSS(MB)\", \"VSZ(MB)\", \$$6 } NR>1 { printf \"%-10s %-10s %-10s %-10.2f %-10.2f %s\\n\", \$$1, \$$2, \$$3, (\$$4/1024), (\$$5/1024), \$$6 }'"
# 查看资源使用前10
n?=10
top:
	@$(SSH_CMD) ${TOP_CMD} | head -n $$(($(n) + 1))

top-p:
	@$(SSH_CMD) ${CPU_CMD} | head -n $$(($(n) + 1))


#内存总体使用情况
mem:
	@$(SSH_CMD) "echo 'Memory Usage:' && free -m | awk '/Mem/ { printf(\"%sM/%sM (%.2f%%)\\n\", \$$3, \$$2, (\$$3/\$$2)*100) }' "
# CPU总体使用情况
CPU_CMD = "ps -eo pid,%cpu,%mem,rss,vsz,cmd --sort -%cpu | awk 'NR==1 { printf \"%-10s %-10s %-10s %-10s %-10s %s\\n\", \$$1, \$$2, \$$3, \"RSS(MB)\", \"VSZ(MB)\", \$$6 } NR>1 { printf \"%-10s %-10s %-10s %-10.2f %-10.2f %s\\n\", \$$1, \$$2, \$$3, (\$$4/1024), (\$$5/1024), \$$6 }'"

cpu:
	@$(SSH_CMD) "ps -A -o %cpu | awk '{s+=\$$1} END {print \"CPU 使用率: \"s\"%\"}'"
#磁盘总体使用情况
disk:
	@$(SSH_CMD) 'echo "根目录磁盘使用情况:" && echo "-----------------------------------" && \
	df -h | grep -E "^.* /$$" | awk '\''{ printf "总容量: %-10s 已用: %-10s 可用: %-10s 使用率: %s\n", $$2, $$3, $$4, $$5 }'\'' && \
	echo "-----------------------------------"'
#网络使用情况
net:
	@$(SSH_CMD) 'echo "网络接口使用情况:" && echo "-----------------------------------" && \
	ifconfig | awk '\''BEGIN {OFS="\t"} /^[a-zA-Z0-9]/ {iface=$$1} /bytes/ {if($$0 ~ /RX packets/) {rx=$$5} else if($$0 ~ /TX packets/) {tx=$$5; printf "接口: %-8s 接收: %-5.2fMB 发送: %-5.2fMB\n", iface, (rx/1024/1024), (tx/1024/1024)} }'\'' && \
	echo "-----------------------------------"'
